package com.lyh.web.controller.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.common.core.domain.BaseEntity;
import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.enums.GoodsSortRuleEnum;
import com.lyh.common.utils.SecurityUtils;
import com.lyh.common.utils.StringUtils;
import com.lyh.system.biz.IOrderBiz;
import com.lyh.system.domain.req.*;
import com.lyh.system.domain.resp.OrderWebResq;
import com.lyh.system.domain.resp.UserIncomeResp;
import com.lyh.system.domain.vo.BuyGoodsVo;
import com.lyh.system.domain.vo.OrderVo;
import com.lyh.system.domain.vo.PayVo;
import com.lyh.system.mapper.OrderMapper;
import com.lyh.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.lyh.common.annotation.Log;
import com.lyh.common.core.controller.BaseController;
import com.lyh.common.core.domain.AjaxResult;
import com.lyh.common.enums.BusinessType;
import com.lyh.system.domain.Order;
import com.lyh.system.service.IOrderService;
import com.lyh.common.utils.poi.ExcelUtil;
import com.lyh.common.core.page.TableDataInfo;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2023-05-11
 */
@Api(value = "订单管理",description = "订单管理")
@RestController
@RequestMapping("/app/order")
public class OrderController extends BaseController
{
    @Autowired
    private IOrderService orderService;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IOrderBiz orderBiz;


    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询订单列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(required = false) String sortRule)
    {
        List<Order> list = orderMapper.selectList(new LambdaQueryWrapper<>());

        if (isNotBlank(sortRule)) {
            if (GoodsSortRuleEnum.ASC.name().equals(sortRule)) {
                list = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                        .orderByAsc(Order::getCreateTime));
            } else if (GoodsSortRuleEnum.DESC.name().equals(sortRule)) {
                list = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                        .orderByDesc(Order::getCreateTime));
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 导出订单列表
     */
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @ApiOperation("订单导出")
    @PostMapping("/export")
    public void  export(HttpServletResponse response,@RequestBody OrderWebReq req)
    {
        req.setPageNum(null);
        req.setPageSize(null);
        List<OrderWebResq> list = orderService.selectOrderListByWeb(req);
        ExcelUtil<OrderWebResq> util = new ExcelUtil<OrderWebResq>(OrderWebResq.class);
         util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderService.selectOrderById(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Order order)
    {
        return toAjax(orderService.insertOrder(order));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Order order)
    {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(orderService.deleteOrderByIds(ids));
    }

    /**
     * 查询商家订单列表
     */
    @GetMapping("/webPageList")
    @ApiOperation("订单管理")
    public TableDataInfo webList(OrderWebReq req)
    {
        startPage();
        List<OrderWebResq> list = orderService.selectOrderListByWeb(req);
        return getDataTable(list);

    }

    @ApiOperation("发货")
    @PostMapping("/editLogistics")
    public AjaxResult editLogistics(@Validated @RequestBody OrderWLReq req){
        orderService.editLogistics(req);
        return AjaxResult.success();
    }

    @ApiOperation("修改地址")
    @PostMapping("/editAddress")
    public AjaxResult editAddress(@Validated @RequestBody OrderAddrReq req){
        orderService.editAddress(req);
        return AjaxResult.success();
    }

    @ApiOperation("无物流")
    @PostMapping("/noAddress")
    public AjaxResult noAddress(@Validated @RequestBody OrderNoAddrReq req){
        orderService.noAddress(req);
        return AjaxResult.success();
    }

    @ApiOperation("退款")
    @PostMapping("/refundOrder")
    @Log(title = "退款", businessType = BusinessType.INSERT)
    public AjaxResult refundOrder(@Validated @RequestBody OrderNoAddrReq req){
        return orderService.refundOrder(req);
    }


    /**
     * 下单
     */
    @PostMapping("/createOrder")
    @Log(title = "下单", businessType = BusinessType.INSERT)
    public AjaxResult createOrder(@RequestBody BuyGoodsVo bgv){
        Long orderId = orderService.createOrder(bgv);
        return AjaxResult.success(orderId.toString());
    }

    /**
     * 支付
     */
    @ApiOperation("支付")
    @PostMapping("/pay")
    @Log(title = "支付", businessType = BusinessType.INSERT)
    public AjaxResult pay(@RequestBody PayVo payVo){
        return orderService.pay(payVo);
    }

    @GetMapping("/orderList")
    public AjaxResult list()
    {
       SysUser user = SecurityUtils.getLoginUser().getUser();
        List<OrderVo> orders = orderMapper.getOrder(user.getUserId());
        return AjaxResult.success(orders);
    }


}
